/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package form;

import io.resource.DataRef;
import io.resource.ResourceDelegate;
import java.awt.Color;
import java.awt.Component;
import java.awt.Window;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author Robert A. Cherry
 */
public class ConflictMonitor extends javax.swing.JDialog {

    // Variable Declaration
    // Project Classes
    private DataRef conflict;
    private ResourceDelegate delegate;
    // End of Variable Declaration

    public ConflictMonitor(Window window, ResourceDelegate delegate, boolean modal) {
        super(window);
        setModal(modal);
        initComponents();

        //
        this.delegate = delegate;

        //
        init();
    }

    private void init() {

        // Create the table model
        final DefaultTableModel tableModel = new DefaultTableModel();

        // Create our column identifiers (the labels)
        final String[] columnIdentifiers = new String[]{"Class", "Display Name", "Editor Name", "Editor Id", "Package Id"};

        //
        final DataRef[] references = delegate.detectConflictions();

        // Out index
        int dataIndex = 0;

        // Out data vector
        final String[][] dataVector = new String[references.length][];

        // Iterate over the node list
        for (int i = 0; i < references.length; i++) {

            //
            final DataRef reference = references[i];

            // Grab the referenceName from the attributes of this node
            final String className = reference.getResource().getClass().getSimpleName();
            final String displayName = reference.getDisplayName();
            final String referenceName = reference.getEditorName();
            final String referenceID = reference.getEditorId();
            final String packageID = reference.getPackageId();

            // Set the data vector
            dataVector[dataIndex] = new String[]{className.substring(1, className.length()), displayName, referenceName, referenceID, packageID};
            dataIndex++;
        }

        //
        conflictJLabel.setText("Conflicted Entries: " + dataIndex);

        // Set the data vector and column indentifiers
        tableModel.setDataVector(dataVector, columnIdentifiers);

        // Apply the table model and the data vector
        manifestJTable.setModel(tableModel);
        manifestJTable.getTableHeader().setReorderingAllowed(false);
    }

    private void manifestJTableCustomRenderer(Component component, TableCellRenderer renderer, int row, int col) {

        // The color for confliction
        final Color conflicted = new Color(243, 5, 5);

        // Delegate updated to detect conflicts; so some degree. (I may make it more full proof in the future)
        component.setForeground(conflicted);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonJPanel = new javax.swing.JPanel();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
        resolveJButton = new javax.swing.JButton();
        filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(8, 0), new java.awt.Dimension(8, 0), new java.awt.Dimension(8, 32767));
        closeJButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        manifestJTable = new javax.swing.JTable() {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {

                final Component component = super.prepareRenderer(renderer, row, col);

                // Do outside of this
                manifestJTableCustomRenderer(component, renderer, row, col);

                // Return the component
                return component;
            }

            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }
        };
        jPanel1 = new javax.swing.JPanel();
        conflictJLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Monitoring Conflicts in Resources");
        setMinimumSize(new java.awt.Dimension(417, 330));
        setResizable(false);

        buttonJPanel.setLayout(new javax.swing.BoxLayout(buttonJPanel, javax.swing.BoxLayout.LINE_AXIS));
        buttonJPanel.add(filler1);

        resolveJButton.setText("Resolve");
        resolveJButton.setEnabled(false);
        resolveJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resolveJButtonActionPerformed(evt);
            }
        });
        buttonJPanel.add(resolveJButton);
        buttonJPanel.add(filler2);

        closeJButton.setText("Close");
        closeJButton.setMaximumSize(new java.awt.Dimension(88, 23));
        closeJButton.setMinimumSize(new java.awt.Dimension(88, 23));
        closeJButton.setPreferredSize(new java.awt.Dimension(88, 23));
        closeJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeJButtonActionPerformed(evt);
            }
        });
        buttonJPanel.add(closeJButton);

        manifestJTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        manifestJTable.setFillsViewportHeight(true);
        manifestJTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                manifestJTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(manifestJTable);

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));

        conflictJLabel.setText("Conflicted Entries: ");
        conflictJLabel.setMaximumSize(new java.awt.Dimension(132, 20));
        conflictJLabel.setMinimumSize(new java.awt.Dimension(132, 20));
        conflictJLabel.setPreferredSize(new java.awt.Dimension(132, 20));
        jPanel1.add(conflictJLabel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 397, Short.MAX_VALUE)
                    .addComponent(buttonJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closeJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeJButtonActionPerformed

        // Close the Manifest Viewer
        setVisible(false);
    }//GEN-LAST:event_closeJButtonActionPerformed

    private void manifestJTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_manifestJTableMouseClicked

        // TODO add your handling code here:
        final int row = manifestJTable.rowAtPoint(evt.getPoint());
        final int col = manifestJTable.columnAtPoint(evt.getPoint());

        //
        final int clickCount = evt.getClickCount();

        //
        if (row > -1 && col > -1) {

            // Grab the reference at point
            final String displayName = String.valueOf(manifestJTable.getValueAt(row, 1));
            final String referenceName = String.valueOf(manifestJTable.getValueAt(row, 2));
            final String referenceID = String.valueOf(manifestJTable.getValueAt(row, 3));

            // Find it by its referenceID, referenceName, and displayName
            conflict = delegate.getReference(ResourceDelegate.ID_EDITOR_REFERENCE, referenceID);

            // Grab all others and check for completely similar entries
            for (int j = 0; j < manifestJTable.getRowCount(); j++) {

                // Current id
                final String currentDN = String.valueOf(manifestJTable.getValueAt(j, 1));
                final String currentEN = String.valueOf(manifestJTable.getValueAt(j, 2));
                final String currentEI = String.valueOf(manifestJTable.getValueAt(j, 3));

                if (j != row) {

                    // They have completely conflicting information?
                    if (currentDN.equalsIgnoreCase(displayName) && currentEI.equalsIgnoreCase(referenceID) && currentEN.equalsIgnoreCase(referenceName)) {

                        // Display an error and return
                        final String msg = "Two resources have the exact same information and thus cannot be distinguished.";
                        
                        JOptionPane.showMessageDialog(this, msg);
                        
                        //
                        return;
                    }
                }
            }

            // Detect double click
            if (clickCount == 2) {

                // Enable the resolve button
                resolveJButton.setEnabled(true);
            } else {

                // Do they match
                resolveJButton.setEnabled(false);
            }
        } else {

            // Disable the resolve button
            resolveJButton.setEnabled(false);
        }
    }//GEN-LAST:event_manifestJTableMouseClicked

    private void resolveJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resolveJButtonActionPerformed

        // Show the conflict resolver
        final ConflictResolver resolver = new ConflictResolver(this, delegate, conflict, true);
        resolver.setLocationRelativeTo(this);
        resolver.setVisible(true);
    }//GEN-LAST:event_resolveJButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonJPanel;
    private javax.swing.JButton closeJButton;
    private javax.swing.JLabel conflictJLabel;
    private javax.swing.Box.Filler filler1;
    private javax.swing.Box.Filler filler2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable manifestJTable;
    private javax.swing.JButton resolveJButton;
    // End of variables declaration//GEN-END:variables
}
